package middleware

import (
	"fmt"
	"github.com/starmotioncf/common/log"
	redis2 "github.com/starmotioncf/common/redis"
	"github.com/starmotioncf/soutchatinternal/constant"
	"github.com/starmotioncf/soutchatpkg/jwt"
	"go.uber.org/zap"

	"github.com/gin-gonic/gin"
)

// RateLimitConfig 接口速率限制

type RateLimitMiddleware struct {
	rateLimit *redis2.RateLimiter
}

func NewRateLimitMiddleware(rateLimit *redis2.RateLimiter) *RateLimitMiddleware {
	return &RateLimitMiddleware{
		rateLimit: rateLimit,
	}
}

func (m *RateLimitMiddleware) Handle(ctx *gin.Context) {
	tp, ok := ctx.Value(constant.CtxToken).(*jwt.TokenClaims)
	if !ok || tp.Uid == 0 {
		log.WithContext(ctx).Debug("uid=0,不限制")
		ctx.Next()
		return
	}
	limitKey := fmt.Sprint("%d:%s:%s", tp.Uid, ctx.Request.Method, ctx.Request.URL.Path)
	if m.rateLimit.Allow(limitKey) {
		log.WithContext(ctx).Error("访问太频繁", zap.String("limitKey", limitKey))
		return
	}
	ctx.Next()
}
